<template>
    <div class="automation-list">
        <!-- 页面标题栏 -->
        <div class="page-title">
            <el-button link class="back-btn" @click="handleBack">
                <el-icon>
                    <ArrowLeft />
                </el-icon>
            </el-button>
            <div class="title">自动化控制</div>
        </div>

        <div class="content">
            <el-button type="primary" @click="handleAdd" class="add-btn">
                <el-icon class="mr-1">
                    <Plus />
                </el-icon>添加自动化
            </el-button>

            <div v-if="automationList.length > 0" class="automation-cards">
                <el-card v-for="(item, index) in automationList" :key="index" class="automation-card" shadow="hover">
                    <div class="automation-item">
                        <div class="left">
                            <div class="icon-wrapper">
                                <el-icon>
                                    <Clock />
                                </el-icon>
                            </div>
                            <div class="info">
                                <div class="name">{{ item.name }}</div>
                                <div class="desc">
                                    <template v-if="item.conditions && item.conditions.length">
                                        当
                                        <template v-for="(condition, cIndex) in item.conditions" :key="cIndex">
                                            <template v-if="cIndex > 0">
                                                <span class="connector">{{ item.conditionMode === 'all' ? ' 且 ' : ' 或 '
                                                    }}</span>
                                            </template>
                                            <span class="condition">{{ formatCondition(condition) }}</span>
                                        </template>
                                        时，
                                    </template>
                                    <template v-if="item.devices && item.devices.length">
                                        <span class="devices">{{ getDeviceNames(item.devices) }}</span>
                                        将
                                    </template>
                                    <template v-if="item.actions && item.actions.length">
                                        <span class="action">{{ formatActions(item.actions) }}</span>
                                    </template>
                                </div>
                            </div>
                        </div>
                        <div class="right">
                            <div class="action-btns">
                                <el-button type="primary" link @click="handleEdit(item)">
                                    编辑
                                </el-button>
                                <el-divider direction="vertical" />
                                <el-button type="danger" link @click="handleDelete(index)">
                                    删除
                                </el-button>
                            </div>
                            <el-switch v-model="item.enabled" @change="handleStatusChange(index)"
                                active-color="var(--color-primary)" inactive-color="var(--color-border)" />
                        </div>
                    </div>
                </el-card>
            </div>

            <!-- 空状态展示 -->
            <div v-else class="empty-state">
                <el-empty description="还没有自动化任务" :image-size="200">
                    <template #image>
                        <el-icon class="empty-icon">
                            <Connection />
                        </el-icon>
                    </template>
                    <el-button type="primary" @click="handleAdd">
                        <el-icon class="mr-1">
                            <Plus />
                        </el-icon>
                        创建自动化
                    </el-button>
                </el-empty>
            </div>
        </div>

        <AutomationDialog v-model="dialogVisible" :automation-data="currentAutomation" @save="handleSave" />
    </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { Plus, Clock, ArrowLeft, Connection } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import AutomationDialog from './components/AutomationDialog.vue'

const router = useRouter()
const dialogVisible = ref(false)
const currentAutomation = ref(null)
const automationList = ref([])

// 返回上一级
const handleBack = () => {
    router.back()
}

// 设备选项配置（用于匹配设备名称）
const deviceOptions = [
    {
        label: '照明',
        value: 'light',
        children: [
            { label: '1楼前排教室灯光', value: 'floor1_front' },
            { label: '1楼后排教室灯光', value: 'floor1_back' },
            { label: '1楼2教室灯光', value: 'floor1_room2' }
        ]
    },
    {
        label: '空调',
        value: 'ac',
        children: [
            { label: '1楼空调', value: 'floor1_ac' },
            { label: '2楼空调', value: 'floor2_ac' }
        ]
    }
]

// 查找设备名称的函数
const findDeviceName = (value) => {
    for (const group of deviceOptions) {
        const device = group.children.find(child => child.value === value)
        if (device) return device.label
    }
    return value
}

// 获取设备名称列表
const getDeviceNames = (devices) => {
    if (!Array.isArray(devices)) return ''
    return devices.map(device => {
        if (Array.isArray(device)) {
            return device.map(findDeviceName).pop()
        }
        return findDeviceName(device)
    }).join('、')
}

// 格式化条件显示
const formatCondition = (condition) => {
    if (condition.type === 'time') {
        const timeString = condition.timeValue ? dayjs(condition.timeValue).format('HH:mm') : ''
        return `${condition.frequency === 'daily' ? '每天' : condition.frequency === 'workday' ? '工作日' : '周末'} ${timeString}`
    } else if (condition.type === 'sensor') {
        return `人体传感器${condition.sensorType === 'motion' ? '检测到' : ''}${condition.status === 'present' ? '有人' : '无人'}`
    }
    return ''
}

// 格式化动作显示
const formatActions = (actions) => {
    return actions.map(action => {
        switch (action.type) {
            case 'on': return '开启'
            case 'off': return '关闭'
            case 'adjust': return '调节'
            default: return action.type
        }
    }).join('、')
}

const handleAdd = () => {
    currentAutomation.value = {
        name: '自动化任务1',
        enabled: true,
        conditionMode: 'any',
        conditions: [{
            type: 'time',
            frequency: 'daily',
            timeValue: null
        }],
        devices: [],
        actions: [{
            type: ''
        }]
    }
    dialogVisible.value = true
}

const handleEdit = (item) => {
    currentAutomation.value = { ...item }
    dialogVisible.value = true
}

const handleDelete = (index) => {
    ElMessageBox.confirm(
        '确定要删除此自动化任务吗？',
        '提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        automationList.value.splice(index, 1)
    }).catch(() => { })
}

const handleStatusChange = (index) => {
    const item = automationList.value[index]
    console.log('Status changed:', item.name, item.enabled)
}

const handleSave = (data) => {
    if (currentAutomation.value?.id) {
        // 更新现有自动化
        const index = automationList.value.findIndex(item => item.id === data.id)
        if (index > -1) {
            automationList.value[index] = data
        }
    } else {
        // 添加新自动化
        automationList.value.push({
            ...data,
            id: Date.now(),
            enabled: true
        })
    }
    dialogVisible.value = false
}
</script>

<style lang="scss" scoped>
.automation-list {
    .page-title {
        display: flex;
        align-items: center;
        gap: var(--gap-small);
    }

    .content {
        padding: 0 var(--gap-normal);

        .add-btn {
            margin-bottom: var(--gap-normal);
        }
    }

    .automation-cards {
        display: flex;
        flex-direction: column;
        gap: var(--gap-normal);

        .automation-card {
            transition: all 0.3s ease;

            &:hover {
                transform: translateY(-2px);
            }
        }

        .automation-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            min-height: 64px;

            .left {
                display: flex;
                align-items: center;
                gap: var(--gap-normal);

                .icon-wrapper {
                    width: 40px;
                    height: 40px;
                    border-radius: 8px;
                    background-color: var(--color-background);
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    color: var(--color-primary);
                    font-size: 20px;
                }

                .info {
                    .name {
                        font-size: var(--font-size-base);
                        font-weight: var(--font-weight-primary);
                        color: var(--color-text-primary);
                        margin-bottom: 8px;
                    }

                    .desc {
                        font-size: var(--font-size-small);
                        color: var(--color-text-regular);
                        line-height: 1.6;

                        .condition {
                            color: var(--color-primary);
                            font-weight: var(--font-weight-primary);
                        }

                        .connector {
                            color: var(--color-text-regular);
                            margin: 0 4px;
                        }

                        .devices {
                            color: var(--color-text-primary);
                            font-weight: var(--font-weight-primary);
                        }

                        .action {
                            color: var(--color-success);
                            font-weight: var(--font-weight-primary);
                        }
                    }
                }
            }

            .right {
                display: flex;
                align-items: center;
                gap: var(--gap-normal);

                .action-btns {
                    display: flex;
                    align-items: center;
                    gap: var(--gap-small);

                    .el-divider {
                        height: 16px;
                        margin: 0 4px;
                    }
                }

                :deep(.el-switch) {
                    --el-switch-on-color: var(--color-primary);
                    --el-switch-off-color: var(--color-border);
                }
            }
        }
    }

    .empty-state {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 400px;
        margin-top: 40px;

        :deep(.el-empty) {
            .empty-icon {
                font-size: 100px;
                color: var(--color-primary);
                opacity: 0.5;
            }

            .el-empty__description {
                margin-top: 20px;
                font-size: var(--font-size-base);
                color: var(--color-text-secondary);
            }

            .el-button {
                margin-top: 20px;
            }
        }
    }
}
</style>